Tạo một thư viện JS

Viết một thư viện, dù chỉ vài chục dòng, mang lại rất nhiều kiến thức hữu ích. Mình sẽ viết theo những hiểu biết của mình. Hi vọng các bạn sẽ có cho mình nhiều kinh nghiệm. Thư viện mình viết có chức năng rất đơn giản: Một db đơn giản với lưu FILE dạng Blob.

Tạo thư mục git

Đầu tiên các bạn tạo remote repostory trên git server yêu thích của bạn, trong tuts này mình sẽ dùng github

Tạo git folder ở local:

1
git init [Tên dụ án git]

Thêm remote cho git folder:

1
git remote add origin [Địa chỉ git remote của bạn]

Cấu trúc thư mục

Thư mục src sẽ chứa code nguồn, thư mục tests để chạy test, thư mục dist sẽ chứa code release.

Cài các depedencies

Cấu hình webpack

Tạo file webpack.config.js:

1
2
npm i webpack-cli @webpack-cli/init
npx webpack-cli init

Sau đó sửa lại như sau:

1
2
3
4
5
6
7
8
9
10
11
12

var libraryName = 'mamaDB'; // Hoặc tên thư viện của bạn
var outputFile = libraryName + '.js';

...
output: {
path: __dirname+'/dist',
filename: outputFile,
library: libraryName,
libraryTarget: 'umd',
umdNamedDefine: true
},

Module hóa code

Đầu tiên ta có code ban đầu:

Nếu các hàm có liên quan đến nhau, hoặc chỉ được gọi ở ngay tại scope đó thì nên để chung. Còn không, chia các hàm thành các file riêng. Khi import sẽ dễ đọc hơn. Một cách khác nữa để import, export nhiều từ một file là sử dụng destructuring:

Test với mocha và chai

Test là một công việc rất quan trọng và cần thiết trong lập trình. Hiện tại chúng ta ít còn phải test bằng tay do việc ra đời của các công cụ test rất mạnh mẽ. Ở đây mình sử dụng Mocha để test và Chai để assert.
Vì thư viện trên trình duyệt nên test trên môi trường trình duyệt (vì js trên server với trên browser có nhiều khác biệt về các API). Code test trình duyệt:

  • HTML

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <!DOCTYPE html>
    <html>
    <head>
    <title>Mocha Tests</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/6.1.2/mocha.min.css">
    </head>
    <body>
    <div id="mocha"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/6.1.2/mocha.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script>
    <script>mocha.setup('bdd')</script>

    <!-- load code you want to test here -->
    <script src="../dist/mamaDB.js"></script>
    <script>
    let expect = chai.expect;
    </script>
    <!-- load your test files here -->
    <script src="./test.js"></script>
    <script>
    mocha.run();
    </script>
    </body>
    </html>
  • JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
describe('mamaDB',()=>{
let db = null;
beforeEach(() => {
db = new mamaDB();
});
describe('after initization',()=>{
it('should return an error after getItem(anykey)', ()=>{
expect(db.getItem("key").message).to.equal("Unable to get item");
});
it('should return an error after getItem(anykey) with anykey is not string',()=>{
expect(db.getItem(1).message).to.equal("Key is not a string");
})
})
describe('Test putItem function',()=>{
it('should return an err if "key" is not string',()=>{
expect(db.putItem(null,"key").message).to.equal("invalid type")
})
it('should return an err if "key" is null',()=>{
expect(db.putItem(null,null).message).to.equal("invalid type")
})
it('should return an err if "file" is not a FILE',()=>{
expect(db.putItem("D","key").message).to.equal("invalid type")
})
it('should return an err if "file" is null',()=>{
expect(db.putItem(null,"key").message).to.equal("invalid type")
})
it('should return key if succes add to db',()=>{
expect(db.putItem(new File([JSON.stringify("Text")],"ex.json"),"key")).to.equal("key")
})
})
describe('Test getItem function',()=>{
beforeEach(()=>{
db.putItem(db.putItem(new File([JSON.stringify("Text")],"ex.json"),"key"));
})
it('Should return item if valid key');
it('Should return error if key is not string');
it('Should return error item if key is null');
it('Should not return item if not valid key');
})
});

Mình sử dụng liveserver ngay trong visual studio code để tự cập nhập lại code:

Hàm descbrice dùng để mô tả đoạn test. Hàm it để định nghĩa code cho các đoạn code.

Build code

Kết